package com.topscomm.meet.job;

import com.topscomm.basic.util.Config;
import com.topscomm.tap.common.ParameterCache;
import com.topscomm.tap.util.ErrorLogUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.yanceyzhang.commons.wx.chatbot.WxChatbotClient;
import com.yanceyzhang.commons.wx.chatbot.message.MarkdownMessage;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Properties;


@Aspect
@Component
public class wxJobAlarm {
    //定义系统和环境变量
    @Value("${spring.application.name}")
    String appname;
    @Value("${spring.profiles.active}")
    String profile;

    public wxJobAlarm(){

    }

    /**
     * 切入点
     */
    @Pointcut("@target(com.xxl.job.core.handler.annotation.JobHandler) && execution(* execute(..)) && args(java.lang.String)")
    public  void jobCut(){
    }

    /**
     * 获取任务返回结果后进行异常通知
     * @param joinPoint
     * @param res
     */
    @AfterReturning(pointcut = "jobCut()",returning = "res")
    public void PushException(JoinPoint joinPoint, ReturnT res){
        try {
            if (ReturnT.FAIL_CODE == res.getCode()) {
                String key = ParameterCache.getValue("wxJobAlarm_key", "a31a4dd9-2359-4839-a095-0e7cf397b580");
                String jobName = joinPoint.getSignature().getDeclaringTypeName() + ":" + joinPoint.getSignature().getName();
                StringBuilder content = new StringBuilder("<font color=\"warning\">xxlJob任务执行失败!!</font>\n");
                //拼接markdown
                content.append(">系统名称:").append(appname).append("\n");
                content.append(">环境:").append(profile).append("\n");
                content.append(">任务名称:").append(jobName).append("\n");
                content.append(">任务参数:").append(joinPoint.getArgs()[0]).append("\n");
                content.append(">任务返回:").append(res.getMsg()).append("\n");
                //xxljob地址
                String xxljob_address = Config.getInstance().getValue("xxljob.addresses", "");
                content.append(">任务执行器地址:").append("[").append(xxljob_address).append("]").append("(").append(xxljob_address).append(")").append("\n");
                MarkdownMessage message = new MarkdownMessage();
                message.add(content.toString());
                WxChatbotClient.send(key, message);
            }
        }catch (Exception e){
            e.printStackTrace();
            ErrorLogUtil.writeLog(e);
        }
    }
}
